package cn.lanqiao.facelogin.controller;

import cn.lanqiao.facelogin.service.LoginService;
import cn.lanqiao.facelogin.utils.GiteeHttpClient;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.net.URLEncoder;
import java.util.UUID;


@Controller
public class GiteeController {
    /**
     * gitee授权中提供的 appid 和 appkey
     */
    @Value("${gitee.oauth.clientid}")
    public String CLIENTID;

    @Value("${gitee.oauth.clientsecret}")
    public String CLIENTSECRET;

    @Value("${gitee.oauth.callback}")
    public String URL;

    @Autowired
    private LoginService loginService;

    /**
     * 请求授权页面
     */
    @GetMapping(value = "/gitee/auth")
    public String giteeAuth(HttpSession session) {
        // 用于第三方应用防止CSRF攻击
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        session.setAttribute("state", uuid);

        // Step1：获取Authorization Code
        String url = "https://gitee.com/oauth/authorize?response_type=code" +
                "&client_id=" + CLIENTID +
                "&redirect_uri=" + URLEncoder.encode(URL) +
                "&state=" + uuid +
                "&scope=user_info";

        return "redirect:" + url;
    }

    /**
     * 授权回调
     */
    @GetMapping(value = "/success")
    public String qqCallback(HttpServletRequest request, Model model) throws Exception {
        HttpSession session = request.getSession();
        // 得到Authorization Code
        String code = request.getParameter("code");
        // 我们放在地址中的状态码
        String state = request.getParameter("state");
        String uuid = (String) session.getAttribute("state");

        // 验证信息我们发送的状态码
        if (null != uuid) {
            // 状态码不正确，直接返回登录页面
            if (!uuid.equals(state)) {
                return "redirect:http://localhost:8080";
            }
        }

        // Step2：通过Authorization Code获取Access Token
        String url = "https://gitee.com/oauth/token?grant_type=authorization_code" +
                "&client_id=" + CLIENTID +
                "&client_secret=" + CLIENTSECRET +
                "&code=" + code +
                "&redirect_uri=" + URL;
        JSONObject accessTokenJson = GiteeHttpClient.getAccessToken(url);

        // Step3: 获取用户信息
        url = "https://gitee.com/api/v5/user?access_token=" + accessTokenJson.get("access_token");
        JSONObject jsonObject = GiteeHttpClient.getUserInfo(url);
        String uName = String.valueOf(jsonObject.get("name"));
        String tokenId = String.valueOf(jsonObject.get("id"));
        if (loginService.findTokenId(tokenId).getData() == null) {
            return "redirect:complete.html?tokenId=" + tokenId;
        } else {
            String tokenIdTel = loginService.findTokenIdTel(tokenId);
            model.addAttribute("name", jsonObject.get("name"));
            /**
             * 获取到用户信息之后，就该写你自己的业务逻辑了
             */
            return "redirect:userinfo.html?tokenId=" + tokenIdTel;
        }


    }
}
